<?php

namespace Wap\Model;

class OrderModel extends BaseModel {

    /**
     * 订单结算
     * @param type $userId
     * @return string
     */
    public function checkOrder($userId) {
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = 'Error!';

        $cartId = I('cartId');
        if (empty($cartId)) {
            $rt['info'] = "没有要结算的商品!";
            return $rt;
        }
        $checkCart = $this->checkStock($cartId);
        if ($checkCart['code'] == 0)
            return $checkCart;
        $checkCart = $checkCart['data'];
        if (I('adrid', 0) > 0) {
            $checkCart['address'] = M('user_address')->where('userId=' . $userId . ' and addressId=' . I('adrid'))->find();
        } else {
            $checkCart['address'] = M('user_address')->where('userId=' . $userId)->order('isDefault DESC, addressId DESC')->find();
        }

        if (empty($checkCart['address']))
            $checkCart['address'] = "";
        $checkCart['buyway'] = M('buyway')->field('id,buyCode,buyName,buyConfig')->select();
        $temp = array();
        foreach ($checkCart['buyway'] as $v) {
            if (empty($v['buyConfig'])) {
                unset($v['buyConfig']);
            }
            $temp[] = $v;
        }
        $checkCart['buyway'] = $temp;

        $temp = array();
        foreach ($checkCart['buyway'] as $v) {
            if ($v['buyCode'] == 'supervise') {
                $v['buyConfig'] = json_decode($v['buyConfig'], true);
            }
            $temp[] = $v;
        }
        $checkCart['buyway'] = $temp;
        unset($temp);
        $checkCart['payments'] = M('payments')->field('id,payCode,payName')->select();

        $rt['code'] = 1;
        $rt['info'] = 'Success!';
        $rt['data'] = $checkCart;
        return $rt;
    }

    /**
     * 订单支付
     * @param type $userId
     * @return string
     */
    public function payOrder($userId) {
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = 'Error!';

        $cartId = I('cartId');
        if (empty($cartId)) {
            $rt['info'] = "没有要支付的商品!";
            return $rt;
        }

        $checkCart = $this->checkStock($cartId);
        if ($checkCart['code'] == 0)
            return $checkCart;
        $checkCart = $checkCart['data'];

        $addressId = I('addressId', 0);
        $buywayId = I('buywayId', 0);
        $payId = I('payId', 0);
        $storeId = I('storeId', 0);

        if ($buywayId == 0 || $addressId == 0 || $payId == 0)
            return $rt;

        if ($buywayId == 2) {
            if ($checkCart['goodsSum'] > $checkCart['offlineSum']) {
                $rt['info'] = '购物车中存在不支持线下看货的商品!';
                return $rt;
            }
            if ($storeId == 0) {
                $rt['info'] = '请选择线下看货门店!';
                return $rt;
            }
        }

        if ($addressId == 0) {
            $address = M('user_address')->where('userId=' . $userId)->order('isDefault DESC, addressId DESC')->find();
        } else {
            $address = M('user_address')->where('addressId=' . $addressId)->order('isDefault DESC, addressId DESC')->find();
        }

        $data = array();
        $data['orderSN'] = '51' . (time() - 168805);
        $data['userId'] = $userId;
        $data['areaId1'] = $address['areaId1'];
        $data['areaId2'] = $address['areaId2'];
        $data['areaId3'] = $address['areaId3'];
        $data['userName'] = $address['userName'];
        $data['userAddress'] = $address['province'] . $address['city'] . $address['district'] . $address['address'];
        $data['addressId'] = $address['addressId'];
        $data['userPhone'] = $address['userPhone'];
        $data['userPostCode'] = $address['postCode'];
        $data['createTime'] = date('Y-m-d H:i:s');
        $data['payType'] = $payId;
        $data['buyway'] = $buywayId;
        $data['storeId'] = $storeId;

        if ($buywayId == 3) {
            $supervise = M('buyway')->where('id = 3')->find();
            $supervise['buyConfig'] = json_decode($supervise['buyConfig'], TRUE);
            $data['supPrice'] = $supervise['buyConfig']['supPrice'];
            $data['supPostage'] = $supervise['buyConfig']['postage'];
            $checkCart['priceSum'] += (count($checkCart['shop']) * ($data['supPrice'] + $data['supPostage']));
        }

        $orderIds = array();
        $orderNo = array();
        $_i = 0;

        $goodsArr = array();
        foreach ($checkCart['shop'] as $v) {
            $goodsData = array();
            foreach ($v['goods'] as $vs) {
                //add order
                $_i++;
                $data['orderNo'] = time() - 168800 + $_i;
                $data['shopId'] = $v['shopId'];
                $data['totalMoney'] = $vs['shopPrice'] * $vs['goodsNumber'];
                $data['postage'] = $v['postage'];
                $data['isSource'] = $vs['isSource'];
                $orderId = M('orders')->add($data);
                //addSourceOrder
                if ($vs['isSource'] == 0) {
                    $this->addSourceOrder($vs['goodsId'], $data, $vs['goodsNumber']);
                }
                $orderIds[] = $orderId;
                $orderNo[] = $data['orderNo'];
                //add order_goods
                $goodsData['orderId'] = $orderId;
                $goodsData['orderNo'] = $data['orderNo'];
                $goodsData['goodsId'] = $vs['goodsId'];
                $goodsData['shopId'] = $vs['shopId'];
                $goodsData['goodsNumber'] = $vs['goodsNumber'];
                $goodsData['marketPrice'] = $vs['marketPrice'];
                $goodsData['shopPrice'] = $vs['shopPrice'];
                $goodsData['goodsSize'] = $vs['goodsSize'];
                $goodsData['goodsWeight'] = $vs['goodsWeight'];
                $goodsData['goodsName'] = $vs['goodsName'];
                $goodsData['goodsThumbs'] = $vs['goodsThumbs'];
                $goodsData['isSource'] = $vs['isSource'];
                $ogId = M('order_goods')->add($goodsData);
                if($vs['isSource'] == 0) {
                    D('Wap/Sms')->sendSMScode($vs['shopTel'], array($vs['goodsName']), 'resaleTempId', 'resaleTempId');
                } else {
                    D('Wap/Sms')->sendSMScode($vs['shopTel'], array($vs['goodsName']), 'saleTempId', 'saleTempId');
                }
                $goodsArr[] = $goodsData;
//                $this->decGoodsStock($goodsData['goodsId'], $goodsData['goodsNumber']);
            }
            $this->log_orders($orderId, $userId, '下单成功');
        }

        if (empty($orderIds)) {
            $rt['info'] = '订单处理失败!';
            return $rt;
        }

        if ($payId == 1) {
            $this->cleanCart($cartId);
            $balance = M('users')->where('userId=' . $userId)->getField('userBalance');
            if ($balance < $checkCart['priceSum']) {
                $rt['info'] = '账户余额不足!';
                return $rt;
            }
        }

        if ($payId == 1) {
            $this->cleanCart($cartId);
            $rs = M('users')->where('userId=' . $userId)->setDec('userBalance', $checkCart['priceSum']);
            if (!$rs) {
                $rt['info'] = '余额支付失败!';
                return $rt;
            }
            $this->logBalance($userId, $checkCart['priceSum'], 1, '订单[' . implode(',', $orderNo) . ']支付');
            $this->setPayStatus($orderIds, $userId);
            foreach ($goodsArr as $vg) {
                $this->decGoodsStock($vg['goodsId'], $vg['goodsNumber']);
            }
            $rt['code'] = 1;
            $rt['info'] = '支付成功!';
            $rt['data'] = array('orderSN' => $data['orderSN'], 'priceSum' => $checkCart['priceSum']);
            return $rt;
        }

        $this->cleanCart($cartId);
        $rt['code'] = 1;
        $rt['info'] = '订单提交成功!';
        $rt['data'] = array('orderSN' => $data['orderSN'], 'priceSum' => $checkCart['priceSum']);
        return $rt;
    }

    /**
     * 页面支付状态
     */
    public function wapToPay() {
        $m = M('orders');
        $orderSN = I('orderSN', 0);
        if (strlen($orderSN) == 12) {
            $orderSN = I('orderSN', 0);
            $rs = $m->where('orderSN=' . $orderSN)->field('orderId,orderSN,orderNo,orderStatus,shopId,totalMoney,postage,supPrice,supPostage,payType,buyway,userName,userAddress,userPhone,storeId,createTime,isPay')->select();
            $order = array();
            foreach ($rs as $v) {
                $order['priceSum'] += ($v['totalMoney'] + $v['postage'] + $v['supPrice'] + $v['supPostage']);
                $order['isPay'] += $v['isPay'];
                $order['orderStatus'] += $v['orderStatus'];
                $order['orderSum'] += 1;
                $order['payType'] += $v['payType'];
                $order['buyway'] += $v['buyway'];
            }
            $order['orderSN'] = $orderSN;
 
            return $order;
        } else {
            $orderSN = I('orderSN', 0);
            $order = $m->where('orderNo=' . $orderSN)->field('orderId,orderSN,orderNo,orderStatus,shopId,totalMoney,postage,supPrice,supPostage,payType,buyway,userName,userAddress,userPhone,storeId,createTime,isPay')->find();
            $order['priceSum'] = $order['totalMoney'] + $order['postage'] + $order['supPrice'] + $order['supPostage'];
 
 
            return $order;
        }
    }

    /**
     * 待付款订单支付
     * @return type
     */
    public function toPay($userId) {
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = 'Error!';

        $m = M('orders');

        $orderId = I('orderId', 0);
        if ($orderId == 0)
            return $rt;

        $payId = I('payId', 0);
        if ($payId == 0)
            return $rt;
        $m->where('orderId=' . $orderId . ' and userId=' . $userId)->save(array('payType' => $payId));

        $order = $m->where('orderId=' . $orderId . ' and userId=' . $userId)->field('orderId,orderSN,orderNo,orderStatus,shopId,totalMoney,postage,supPrice,supPostage,payType,buyway,userName,userAddress,userPhone,storeId,createTime')->find();
        if (empty($order))
            return $rt;
        if ($order['orderStatus'] >= 0) {
            $rt['info'] = '订单已经支付!';
            return $rt;
        }
        $getOrderGoods = $this->getOrderGoods($orderId);
        $order['priceSum'] = $getOrderGoods['totalMoney'] + $order['postage'] + $order['supPrice'] + $order['supPostage'];

        if ($payId == 1) {
            $balance = M('users')->where('userId=' . $userId)->getField('userBalance');
            if ($balance < $order['priceSum']) {
                $rt['info'] = '账户余额不足!';
                return $rt;
            }
        }

        if ($payId == 1) {
            $rs = M('users')->where('userId=' . $userId)->setDec('userBalance', $order['priceSum']);
            if (!$rs) {
                $rt['info'] = '余额支付失败!';
                return $rt;
            }
            if ($rs) {
                $this->logBalance($userId, $order['priceSum'], 1, '订单[' . $order['orderNo'] . ']支付');
            }
            foreach ($getOrderGoods['goods'] as $vg) {
                $this->decGoodsStock($vg['goodsId'], $vg['goodsNumber']);
            }
            $this->setPayStatus($orderId, $userId);
            $rt['code'] = 1;
            $rt['info'] = '支付成功!';
            $rt['data'] = array('orderSN' => $order['orderSN'], 'priceSum' => $order['priceSum']);
            return $rt;
        }

        $rt['code'] = 100100 + $payId;
        $rt['info'] = '订单支付处理中!';
        $rt['data'] = array('orderSN' => $order['orderSN'], 'priceSum' => $order['priceSum']);
        return $rt;
    }

    /**
     * 订单日志
     */
    public function log_orders($orderId, $logUserId, $logContent = '') {
        $m = M('log_orders');
        $data = array();
        $data['orderId'] = $orderId;
        $data['logUserId'] = $logUserId;
        $data['logContent'] = $logContent;
        $data['logTime'] = date('Y-m-d H:i:s');
        $rs = $m->add($data);

        return $rs;
    }

    /**
     * 余额日志
     */
    public function logBalance($userId, $price, $logType, $logContent = '') {
        $m = M('log_user_balance');
        $typeName = array(1 => '订单支付', 2 => '充值', 3 => '提现', 4 => '退款', 5 => '转售收益', 6 => '销售收益');
        $data = array();
        $data['userId'] = $userId;
        $data['logContent'] = $logContent;
        $data['price'] = $price;
        $data['logType'] = $logType;
        $data['typeName'] = $typeName[$logType];
        $data['logTime'] = date('Y-m-d H:i:s');
        $rs = $m->add($data);
        return $rs;
    }

    /**
     * 修改商品库存
     */
    public function decGoodsStock($goodsId, $goodsNumber) {
        $m = M('goods');
        $node = $this->getNodeGoodsId($goodsId);
        $rs = $m->where('goodsId in (' . $node . ')')->setDec('goodsStock', $goodsNumber);
        return $rs;
    }

    /**
     * 成功支付修改订单状态
     */
    public function setPayStatus($orderIds, $userId) {
        $m = M('orders');
        if (is_array($orderIds)) {
            foreach ($orderIds as $v) {
                $orderNo = $m->where('orderId=' . $v)->getField('orderNo');
                $m->orderStatus = 0;
                $m->isPay = 1;
                $rs = $m->where('orderNo = ' . $orderNo)->save();
                $this->log_orders($v, $userId, '支付成功');
                $this->logUserProfit($v);
            }
        } else {
            $m->orderStatus = 0;
            $m->isPay = 1;
            $orderNo = $m->where('orderId=' . $orderIds)->getField('orderNo');
            $rs = $m->where('orderNo = ' . $orderNo)->save();
            $this->log_orders($v, $userId, '支付成功');
            $this->logUserProfit($orderIds);
        }
        return;
    }

    /**
     * 清除购物车
     */
    public function cleanCart($cartId) {
        $m = M('shop_cart');
        $rs = $m->where('cartId IN (' . $cartId . ')')->delete();

        return $rs;
    }

    /**
     * 检查商品库存
     * @param type $cartId
     * @return type
     */
    public function checkStock($cartId) {
        $rt = array('code' => 0, 'info' => 'Error!');
        $sql = "SELECT sc.cartId,sc.goodsId,sc.goodsNumber,sc.shopId,sc.shopName,sc.postage,g.goodsName,g.goodsThumbs,g.marketPrice,g.shopPrice,g.goodsSize,g.goodsWeight,g.isOffline,g.goodsStock,g.goodsFlag,g.isSale,g.goodsStatus,g.isDel,g.isSource,s.shopTel "
                . " FROM __PREFIX__shop_cart as sc LEFT JOIN __PREFIX__goods as g ON sc.goodsId = g.goodsId "
                . " LEFT JOIN __PREFIX__shops as s ON g.shopId = s.shopId "
                . " WHERE sc.cartId IN (" . $cartId . ")";
        $data = $this->query($sql);

        if (empty($data)) {
            $rt['info'] = '没有要结算的商品!';
            return $rt;
        }

        $list = array();
        foreach ($data as $v) {
            if ($v['goodsNumber'] > $v['goodsStock']) {
                $rt['info'] = $v['goodsName'] . '库存不足!';
                return $rt;
            }
            if ($v['goodsFlag'] == 0 || $v['isSale'] == 0 || $v['goodsStatus'] == 0 || $v['isDel'] == 1) {
                $rt['info'] = $v['goodsName'] . '已下架!';
                return $rt;
            }
            $list['shop'][$v['shopId']]['shopName'] = $v['shopName'];
            $list['shop'][$v['shopId']]['shopId'] = $v['shopId'];
            $list['shop'][$v['shopId']]['postage'] = $v['postage'];
            $list['shop'][$v['shopId']]['totalMoney'] += ($v['shopPrice'] * $v['goodsNumber']);
            $list['shop'][$v['shopId']]['goods'][] = $v;
            $list['shopPriceSum'] += ($v['shopPrice'] * $v['goodsNumber']);
            $list['postageSum'][$v['shopId']] = $v['postage'];
            $list['offlineSum'] += $v['isOffline'];
            $list['goodsSum'] += 1;
        }
        $temp = array();
        foreach ($list['shop'] as $v) {
            $temp[] = $v;
        }
        $list['shop'] = $temp;
        $list['postageSum'] = array_sum($list['postageSum']);
        $list['priceSum'] = $list['shopPriceSum'] + $list['postageSum'];
        $rt['code'] = 1;
        $rt['info'] = 'Success!';
        $rt['data'] = $list;
        return $rt;
    }

    /**
     * 获取商品信息
     */
    public function getGoodsInfo($goodsId) {
        $sql = "SELECT g.goodsId,s.shopId,g.goodsName,g.goodsThumbs,g.marketPrice,g.goodsStock,g.shopPrice,s.shopName,g.goodsSize,g.goodsWeight,s.postage,g.isOffline "
                . "FROM __PREFIX__goods as g LEFT JOIN __PREFIX__shops as s ON g.shopId = s.shopId "
                . "WHERE goodsFlag=1 AND isSale=1 AND goodsStatus=1 AND isDel = 0 AND goodsId = " . $goodsId;
        $data = $this->queryRow($sql);

        return $data;
    }

    /**
     * 门店列表
     */
    public function lineStore() {
        $m = M('linestore');
        $areaId1 = I('areaId1', 0);
        $areaId2 = I('areaId2', 0);
        $areaId3 = I('areaId3', 0);

        $where = "isShow = 1 ";
        if (!empty($areaId1))
            $where .= " AND areaId1 = " . $areaId1;
        if (!empty($areaId2))
            $where .= " AND areaId2 = " . $areaId2;
        if (!empty($areaId3))
            $where .= " AND areaId3 = " . $areaId3;

        $data = $m->where($where)->field('storeId,storeName,storeAddress,storeTel,province,city,district')->select();

        return $data;
    }

    /**
     * 完成支付订单
     */
    public function complatePay($obj) {

        $orderSN = $obj["out_trade_no"];
        $total_fee = $obj["total_fee"];

        $data = array();
        $data["isPay"] = 1;
        $data["orderStatus"] = 0;

        $rd = array('status' => -1);
        $om = M('orders');
        $length = strlen($orderSN);
        if ($length == 12) {
            $orderIds = $om->where('orderSN = ' . $orderSN)->field('orderId,orderNo,userId')->select();
            foreach ($orderIds as $v) {
                $rs = $om->where("orderNo = " . $v['orderNo'] . "  and orderFlag=1 and orderStatus=-2")->save($data);
                $this->log_orders($v['orderId'], $v['userId'], '支付成功');
                $this->logUserProfit($v['orderId']);
                $goodsList = M('order_goods')->where('orderId=' . $v['orderId'])->select();
                foreach ($goodsList as $vg) {
                    $this->decGoodsStock($vg['goodsId'], $vg['goodsNumber']);
                }
            }
        } else {
            $order = $om->where('orderSN != 0 and orderNo=' . $orderSN)->find();
            $rs = $om->where("orderNo = " . $orderSN . "  and orderFlag=1 and orderStatus=-2")->save($data);
            $this->log_orders($order['orderId'], $order['userId'], '支付成功');
            $this->logUserProfit($order['orderId']);

            $goodsList = M('order_goods')->where('orderNo=' . $orderSN)->select();
            foreach ($goodsList as $vg) {
                $this->decGoodsStock($vg['goodsId'], $vg['goodsNumber']);
            }
        }


        if (false !== $rs) {
            $rd['status'] = 1;
        }

        return $rd;
    }

    /**
     * 添加源头订单
     * @param type $goodsId
     * @param type $data
     * @return type
     */
    private function addSourceOrder($goodsId, $data, $goodsNumber) {
        $m = M('orders');
        $data['orderSN'] = 0;
        $data['isSource'] = 1;
        $goods_resale = M('goods_resale')->where('goodsId=' . $goodsId)->field('sourceId, sshopId')->find();
        $goodsInfo = M('goods')->where('goodsId=' . $goods_resale['sourceId'])->find();
        $data['shopId'] = $goods_resale['sshopId'];
        $data['totalMoney'] = $goodsInfo['shopPrice'] * $goodsNumber;
        $orderId = $m->add($data);

        //add order_goods
        $goodsData['orderId'] = $orderId;
        $goodsData['orderNo'] = $data['orderNo'];
        $goodsData['goodsId'] = $goodsInfo['goodsId'];
        $goodsData['shopId'] = $goodsInfo['shopId'];
        $goodsData['goodsNumber'] = $goodsNumber;
        $goodsData['marketPrice'] = $goodsInfo['marketPrice'];
        $goodsData['shopPrice'] = $goodsInfo['shopPrice'];
        $goodsData['goodsSize'] = $goodsInfo['goodsSize'];
        $goodsData['goodsWeight'] = $goodsInfo['goodsWeight'];
        $goodsData['goodsName'] = $goodsInfo['goodsName'];
        $goodsData['goodsThumbs'] = $goodsInfo['goodsThumbs'];
        $goodsData['isSource'] = $goodsInfo['isSource'];
        $ogId = M('order_goods')->add($goodsData);

        return $orderId;
    }

}
